import type { App, Directive } from 'vue'
import { usePermission } from '@/composables'

export default function setupPermissionDirective(app: App) {
    const { hasPermission } = usePermission()

    function updateElVisible(el: HTMLElement, permission: string | string[]) {
        if (!permission) {
            throw new Error(
                `v-permission需要指定权限: 比如 v-permission="'dept'", v-permission="['user', 'dept]"`
            )
        }
        if (!hasPermission(permission)) {
            el.parentElement?.removeChild(el)
        }
    }

    const permissionDirective: Directive<HTMLElement, string | string[]> = {
        mounted(el, binding) {
            updateElVisible(el, binding.value)
        },
        beforeUpdate(el, binding) {
            updateElVisible(el, binding.value)
        }
    }

    app.directive('permission', permissionDirective)
}
